package com.laughing.httpserver.handler;

import com.laughing.httpserver.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author laughing.sheng <laughing1917@yeah.net/>
 * @date 2018/1/26
 * @see
 */
@Slf4j
public class ResponseHelper {

    /**
     * 关闭流,读取response处理响应发送
     */
    public static void postProcess(HttpServletResponse response, Object responseBody) throws IOException {
        ServletOutputStream stream = response.getOutputStream();
        if (stream != null) {
            if (response.getStatus()==0){
                response.setStatus(404);
            }
            String builderResponse = buildResponse(response, responseBody);
            stream.write(builderResponse.getBytes("UTF-8"));
            stream.flush();
            stream.close();
        }
    }

    private static String buildResponse(HttpServletResponse response, Object responseBody) {

        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1").append(Constant.SPACE).append(response.getStatus()).append(Constant.SPACE)
                .append(Constant.NEWLINE);
        response.getHeaderNames().forEach(s ->
            sb.append(s).append(":").append(Constant.SPACE).append(response.getHeader(s)).append(Constant.NEWLINE)
        );
        if (!StringUtils.isEmpty(responseBody)){
            sb.append("Content-Length").append(":").append(responseBody.toString().length()).append(Constant.SPACE).
                    append(Constant.NEWLINE).append(Constant.NEWLINE).append(responseBody);
        }
        String result=sb.toString();
        log.info("response is {} ",sb.toString());
        return result;
    }
}
